package com.example.blog.web;

import com.example.blog.Exception.AppException;
import com.example.blog.pojo.User;
import com.example.blog.service.UserService;
import com.example.blog.service.impl.UserServiceImpl;
import com.google.code.kaptcha.servlet.KaptchaServlet;


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Date;
import java.text.SimpleDateFormat;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet("/register")
public class RegisterServlet extends AbstractBaseServlet{

    private UserService userService = new UserServiceImpl();

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected Object process(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        //判断验证码是否正确
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //立即删除验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        String code = req.getParameter("code");

        if(token == null && !token.equalsIgnoreCase(code)){
            throw new AppException("LOG007","验证码输入错误");
        }


        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        String birthday = req.getParameter("birthday");

        if(userService.existsUsername(username)){
            throw new AppException("LOG004","该用户名不可用，已经被注册！");
        }

        //true为男，false为女
        Boolean realSex = true;
        if(sex == "true"){
            realSex = true;
        }else{
            realSex = false;
        }


        java.sql.Date date = new Date(simpleDateFormat.parse(birthday).getTime());

        User user = new User(null,username,password,realSex,date);

        userService.registerUser(user);
//        req.getRequestDispatcher("/view/register_success.html").forward(req, resp);
        return  null;
    }
}
